package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName : com.atguigu.springcloud.service.PaymentService
 * @Description : 类描述
 * Created by cyd on 2021-10-20 19:30:42
 */
@Service
@DefaultProperties(defaultFallback = "timeOutDefaultHandler")
public class PaymentService {

    /**
     * 测试正常访问的方法
     */
    @HystrixCommand
    public String paymentInfo_ok(Integer id) {
        // 让正常方法也超时一下，让新配的DefaultBack生效
        int age = 1 / 0;
        return "线程池：" + Thread.currentThread().getName() +
                " paymentInfo_ok,id=" + id;
    }

    /**
     * 测试异常超时的方法
     */
    @HystrixCommand(fallbackMethod = "timeOutHandler", commandProperties = {
            // 设置这个线程的超时时间是2秒
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public String timeOut(Integer id) {
        // 实际上睡了3秒
        int time = 3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() +
                " paymentInfo_timeOut,id=" + id + "  耗时" + time + "s";
    }

    public String timeOutHandler(Integer id) {
        return "线程池：" + Thread.currentThread().getName() +
                " paymentInfo_timeOut,id=" + id + "，最多允许2秒，这个方法超时了，请排查故障";
    }

    /**
     * 默认处理超时的方法
     */
    public String timeOutDefaultHandler() {
        return "线程池：" + Thread.currentThread().getName() +
                "---DefaultFallback";
    }

    //*****************服务熔断********************
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), // 允许失败率
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            // 此处抛出的异常也会被断路器拦截，并响应fallback
            throw new RuntimeException("id=" + id + "-不能负载");
        }
        String uuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "---调用成功，流水号：" + uuid;
    }

    public String paymentCircuitBreaker_fallback(Integer id) {
        return "id 不能负载，请稍后再试，id=" + id;
    }

}
